package com.hj.dapp.common.util;

import com.aliyun.credentials.utils.StringUtils;
import sun.misc.BASE64Decoder;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Base64;

/**
 * @author 胡奥程
 * @version 1.0
 * @date 2024/1/2
 */
public class Base64Util {
    /**
     * base64 编码转换为 BufferedImage
     * @param base64
     * @return
     */
    public static BufferedImage base64ToBufferedImage(String base64) {
        Base64.Decoder decoder = Base64.getDecoder();
        try {
            byte[] byteArray = decoder.decode(base64);
            ByteArrayInputStream bai = new ByteArrayInputStream(byteArray);
            return ImageIO.read(bai);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static Rectangle CalcRotatedSize(Rectangle src, int angel) {
        // if angel is greater than 90 degree, we need to do some conversion
        if (angel >= 90) {
            if (angel / 90 % 2 == 1) {
                int temp = src.height;
                src.height = src.width;
                src.width = temp;
            }
            angel = angel % 90;
        }

        double r = Math.sqrt(src.height * src.height + src.width * src.width) / 2;
        double len = 2 * Math.sin(Math.toRadians(angel) / 2) * r;
        double angel_alpha = (Math.PI - Math.toRadians(angel)) / 2;
        double angel_dalta_width = Math.atan((double) src.height / src.width);
        double angel_dalta_height = Math.atan((double) src.width / src.height);

        int len_dalta_width = (int) (len * Math.cos(Math.PI - angel_alpha
                - angel_dalta_width));
        int len_dalta_height = (int) (len * Math.cos(Math.PI - angel_alpha
                - angel_dalta_height));
        int des_width = src.width + len_dalta_width * 2;
        int des_height = src.height + len_dalta_height * 2;
        return new Rectangle(new Dimension(des_width, des_height));
    }

    private static BufferedImage rotate(Image src, int angel) {
        int src_width = src.getWidth(null);
        int src_height = src.getHeight(null);
        // calculate the new image size
        Rectangle rect_des = CalcRotatedSize(new Rectangle(new Dimension(
                src_width, src_height)), angel);

        BufferedImage res = null;
        res = new BufferedImage(rect_des.width, rect_des.height,
                BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = res.createGraphics();
        res = g2.getDeviceConfiguration().createCompatibleImage(rect_des.width, rect_des.height, Transparency.TRANSLUCENT);
        g2.dispose();
        g2 = res.createGraphics();
        // transform
        g2.translate((rect_des.width - src_width) / 2,
                (rect_des.height - src_height) / 2);
        g2.rotate(Math.toRadians(angel), src_width / 2, src_height / 2);
        g2.setColor(new Color(255, 0, 0));
        g2.setStroke(new BasicStroke(1));
        g2.drawImage(src, null, null);
        g2.dispose();
        return res;
    }


    /**
     * 顺时针旋转
     *
     * @param base64FileStr
     * @param rotate
     * @return
     * @throws IOException
     */
    public static String rotateImage(String base64FileStr, int rotate) throws IOException {
        if (StringUtils.isEmpty(base64FileStr)) {
            return "";
        }

        Base64.Decoder decoder = Base64.getDecoder();
        // Base64解码,对字节数组字符串进行Base64解码并生成文件
        final byte[] byt = decoder.decode(base64FileStr);
        for (int i = 0, len = byt.length; i < len; ++i) {
            // 调整异常数据
            if (byt[i] < 0) {
                byt[i] += 256;
            }
        }
        InputStream input = new ByteArrayInputStream(byt);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        BufferedImage src = ImageIO.read(input);
        BufferedImage des = rotate(src, rotate);
        ImageIO.write(des, "png", out);
        final Base64.Encoder encoder = Base64.getEncoder();
        final byte[] bytes = out.toByteArray();
        return encoder.encodeToString(bytes);
    }

    public static InputStream base64ToStream(String base64string) {
        try {
            byte[] bytes = new byte[0];
            bytes = new BASE64Decoder().decodeBuffer(base64string.trim());
            return new ByteArrayInputStream(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void convertBase64StrToImage(String base64String, String imageFileName) {
        ByteArrayInputStream bais = null;
        try {
            //获取图片类型
            String suffix = imageFileName.substring(imageFileName.lastIndexOf(".") + 1);
            //获取JDK8里的解码器Base64.Decoder,将base64字符串转为字节数组
            byte[] bytes = Base64.getDecoder().decode(base64String);
            //构建字节数组输入流
            bais = new ByteArrayInputStream(bytes);
            //通过ImageIO把字节数组输入流转为BufferedImage
            BufferedImage bufferedImage = ImageIO.read(bais);
            //构建文件
            File imageFile = new File(imageFileName);
            //写入生成文件
            ImageIO.write(bufferedImage, suffix, imageFile);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bais != null) {
                    bais.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }



}
